package com.youjiang.service.impl;

import com.youjiang.dao.ExaminationMapper;
import com.youjiang.dao.entity.Examination;
import com.youjiang.dao.entity.ExaminationExample;
import com.youjiang.model.Question;
import com.youjiang.service.IExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yujia on 2017/11/19.
 */
@Service
public class ExamService implements IExamService {
    @Autowired
    private ExaminationMapper examinationMapper;

    public List<Question> getExamQuestions() {
        List<Question> questions = new ArrayList<Question>();
        ExaminationExample examinationExample = new ExaminationExample();
        List<Examination> examinations = examinationMapper.selectByExample(examinationExample);
        questions = transferExamToQuestion(examinations);
        return questions;
    }

    public List<Question> getExamQuestionsByClassify(String classify) {
        ExaminationExample examinationExample = new ExaminationExample();
        examinationExample.or().andClassifyEqualTo(classify);
        List<Examination> examinations = examinationMapper.selectByExample(examinationExample);

//        Examination 转成 Question
        List<Question> questions = transferExamToQuestion(examinations);

        return questions;
    }

    // exam/questions.json 返回问题 1个 通过分类
    public Question getExamQuestionByClassify(String classify,int number) { //number从0计数
        List<Question> questions = getExamQuestionsByClassify(classify);

        Question question = questions.get(number);
        question.setCurrentNumber(number);
        question.setTotalNumber(questions.size());

        return question;
    }

    public int addExamQuestion(Examination examination) {
        // @TODO 要做个数据验证
        ExaminationExample examinationExample = new ExaminationExample();
        return examinationMapper.insert(examination);
    }

    public List<Question> transferExamToQuestion(List<Examination> examinations){
        List<Question> questions = new ArrayList<Question>();
        for (Examination exam:examinations) {
            Question question = new Question();
            question.setId(exam.getId());
            question.setClassify(exam.getClassify());
            question.setType(exam.getType());
            question.setTitle(exam.getTitle());
//            备选答案
            List<String> answers = new ArrayList<String>();
            answers.add(exam.getAnswera());
            answers.add(exam.getAnswerb());
            answers.add(exam.getAnswerc());
            answers.add(exam.getAnswerd());
            question.setAnswers(answers);
//            正确答案
            question.setCorrectAnswer(exam.getAnswer());
            questions.add(question);
    }
        return questions;
    }


}


